package com.cypher.encryptionanddecryption.fragment.protocol.nb25;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.activity.BluetoothCommunicationActivity;
import com.cypher.encryptionanddecryption.bean.CommunicationBean;
import com.cypher.encryptionanddecryption.fragment.protocol.AbstractProtocolFragment;
import com.cypher.encryptionanddecryption.util.HexUtils;
import com.cypher.encryptionanddecryption.util.SimpleDateFormatUtils;
import com.cypher.encryptionanddecryption.util.Nb25ProtocolUtils;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * 时钟读写界面
 * @author: 古霸天
 * @date: 2020/11/16
 */
public class ClockFragment extends AbstractProtocolFragment implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
    private EditText dateStr;
    private EditText timeStr;
    private Button currentDatetimeBtn;
    private BluetoothCommunicationActivity activity;
    private CommunicationBean bean;

    private Calendar calendar = Calendar.getInstance();

    public ClockFragment(BluetoothCommunicationActivity activity, CommunicationBean bean) {
        this.activity = activity;
        this.bean = bean;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_nb25_clock, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        dateStr = view.findViewById(R.id.clock_date);
        timeStr = view.findViewById(R.id.clock_time);
        currentDatetimeBtn = view.findViewById(R.id.current_datetime_btn);
        readerDatetime();
        initClickHandler();
    }

    /**
     * 渲染日期时间控件
     */
    private void readerDatetime() {
        // 初始化日期时间框
        Date now = new Date();
        dateStr.setText(SimpleDateFormatUtils.dateFormat.format(now));
        timeStr.setText(SimpleDateFormatUtils.timeFormat.format(now));
    }
    /**
     * 初始化点击事件
     */
    private void initClickHandler() {
        // 系统时间按钮点击事件
        currentDatetimeBtn.setOnClickListener((v) -> {
            readerDatetime();
        });

        // 日期输入框点击事件
        dateStr.setOnClickListener((v) -> {
            try {
                calendar.setTime(SimpleDateFormatUtils.dateFormat.parse(dateStr.getText().toString()));
                new DatePickerDialog(activity, this
                        , calendar.get(Calendar.YEAR)
                        , calendar.get(Calendar.MONTH)
                        , calendar.get(Calendar.DAY_OF_MONTH)).show();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });

        // 时间输入框点击事件
        timeStr.setOnClickListener((v) -> {
            try {
                // 获取小时秒需要把日期和时间拼接起来
                StringBuffer datetime = new StringBuffer(dateStr.getText().toString().trim());
                datetime.append(" ").append(timeStr.getText().toString().trim());
                calendar.setTime(SimpleDateFormatUtils.datetimeFormat.parse(datetime.toString()));
                new TimePickerDialog(activity, this
                        , calendar.get(Calendar.HOUR_OF_DAY)
                        , calendar.get(Calendar.MINUTE)
                        , true).show();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 日期设置成功监听
     * @param view
     * @param year
     * @param month
     * @param dayOfMonth
     */
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        StringBuffer dateBuf = new StringBuffer();
        dateBuf.append(year)
                .append("-")
                .append(HexUtils.paddingLeft(String.valueOf(month + 1), 2))
                .append("-")
                .append(HexUtils.paddingLeft(String.valueOf(dayOfMonth), 2));
        dateStr.setText(dateBuf.toString());
    }

    /**
     * 时间设置成功监听
     * @param view
     * @param hourOfDay
     * @param minute
     */
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        StringBuffer timeBuf = new StringBuffer();
        timeBuf.append(HexUtils.paddingLeft(String.valueOf(hourOfDay), 2))
                .append(":")
                .append(HexUtils.paddingLeft(String.valueOf(minute), 2));
        timeStr.setText(timeBuf.toString());
    }

    @Override
    public void fillFragment(String data) {
        // 程序暂停0.2秒后开始渲染数据
        Runnable r = () -> {
            String formatData = Nb25ProtocolUtils.formatReceiveData(data);
            reader(formatData);
        };
        new Handler().postDelayed(r, 200);

    }

    @Override
    public String getHexCode(String rwType) {
        if (StringUtils.equals("read", rwType)) {
            return Nb25ProtocolUtils.getReadCommand(bean.getHexCode(), PROTOCOL_VERSION);
        }
        // 组包
        return Nb25ProtocolUtils.getWriteCommand(bean.getHexCode(), getData(), PROTOCOL_VERSION);
    }

    /**
     * 渲染页面
     * @param data
     */
    private void reader(String data) {
        StringBuffer dateBuf = new StringBuffer();
        dateBuf.append("20").append(data.substring(0, 2))
                .append("-")
                .append(data.substring(2, 4))
                .append("-")
                .append(data.substring(4, 6));
        dateStr.setText(dateBuf.toString());

        StringBuffer timeBuf = new StringBuffer();
        timeBuf.append(data.substring(6, 8))
                .append(":")
                .append(data.substring(8, 10));
        timeStr.setText(timeBuf.toString());

    }

    /**
     * 获取写入数据
     * @return
     */
    private String getData() {
        StringBuffer datetime = new StringBuffer(dateStr.getText().toString().trim());
        datetime.append(" ").append(timeStr.getText().toString().trim());
        try {
            return SimpleDateFormatUtils.format.format(SimpleDateFormatUtils.datetimeFormat.parse(datetime.toString()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

}
